package ua.yandex.prioritymap;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Brothers
 */
public class PriorityMap<K, V> {

    protected class Priority<V> {

        private V val;
        private int priority;

        public Priority(V i, int pr) {
            this.val = i;
            this.priority = pr;
        }

        public V getVal() {
            return this.val;
        }
    }

    private MyMap<K, Priority<V>> phm;

    //public Map<K, Priority<V>> getMap(){return this.phm;}
    public PriorityMap() {
        this.phm = new MyMap<K, Priority<V>>();
    }

    public int size() {
        return this.phm.size();
    }

    public void put(K key, V value) {
        int i = this.phm.size();
        Priority<V> pv = new Priority(value, i);
        this.phm.put(key, pv);
    }

    public V get(K key) {
        if (this.phm.containsKey(key)) {
            return this.phm.get(key).val;
        } else {
            return null;
        }
    }

    public Map.Entry<K, Priority<V>> getMaxVal() {
        int max = 0;
        Map.Entry<K, Priority<V>> ret = null;
        if (!this.phm.isEmpty()) {
            for (Map.Entry<K, Priority<V>> val : this.phm.entrySet()) {
                if (val.getValue().priority > max) {
                    max = val.getValue().priority;
                    ret = val;
                }
            }
        }
        return ret;
    }

    public V peekValueWithProrityKey() {
        Map.Entry<K, Priority<V>> maxVal = getMaxVal();
        return maxVal.getValue().val;
    }

    public V pollValueWithProrityKey() {
        Map.Entry<K, Priority<V>> maxVal = getMaxVal();
        if (maxVal.getKey() != null) {
            this.phm.remove(maxVal.getKey());
        }
        this.phm.sizeMinusOne();
        return maxVal.getValue().val;

    }

    public void printPHM() {
        for (Map.Entry<K, Priority<V>> e : this.phm.entrySet()) {
            System.out.println(e.getKey() + ": " + e.getValue());
        }
    }
}
